const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');

// Tesseract模型路径
const TESSERACT_LOCAL_PATH = path.join(__dirname, '../tessdata');

// 确保Tesseract模型目录存在
if (!fs.existsSync(TESSERACT_LOCAL_PATH)) {
    fs.mkdirSync(TESSERACT_LOCAL_PATH, { recursive: true });
    console.log('Tesseract模型目录已创建:', TESSERACT_LOCAL_PATH);
}

// 要下载的语言文件
const languages = ['eng'];

// 下载地址前缀
const DOWNLOAD_URL_PREFIX = 'https://github.com/tesseract-ocr/tessdata/raw/main/';

// 下载文件函数
async function downloadFile(url, destination) {
    try {
        console.log(`正在下载: ${url}`);
        const response = await fetch(url);
        
        if (!response.ok) {
            throw new Error(`下载失败: ${response.statusText}`);
        }
        
        const fileStream = fs.createWriteStream(destination);
        await new Promise((resolve, reject) => {
            response.body.pipe(fileStream);
            response.body.on('error', reject);
            fileStream.on('finish', resolve);
        });
        
        console.log(`下载完成: ${destination}`);
        return true;
    } catch (error) {
        console.error(`下载出错: ${error.message}`);
        return false;
    }
}

// 下载所有语言文件
async function downloadAllLanguages() {
    console.log('开始下载Tesseract语言文件...');
    
    for (const lang of languages) {
        const url = `${DOWNLOAD_URL_PREFIX}${lang}.traineddata`;
        const destination = path.join(TESSERACT_LOCAL_PATH, `${lang}.traineddata`);
        
        // 检查文件是否已存在
        if (fs.existsSync(destination)) {
            console.log(`文件已存在: ${destination}`);
            continue;
        }
        
        const success = await downloadFile(url, destination);
        if (!success) {
            console.error(`下载失败: ${lang}`);
        }
    }
    
    console.log('所有语言文件下载完成!');
}

// 执行下载
downloadAllLanguages().catch(console.error); 